<template>
  <div style="padding-top: 10px;background-color: #ffffff;">
    <!-- 表单 -->
    <el-form :inline="true" :model="page" class="demo-form-inline">
      <el-form-item label="">
        <el-input v-model="page.queryString" placeholder="药名  /  成分 / 性状 / 功效"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="onSubmit">搜索</el-button>
      </el-form-item>
<!--      <el-form-item>-->
<!--        <el-button  v-if="deleteButton" type="danger" @click="batchDeletion" icon="el-icon-delete">批量删除</el-button>-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-refresh" @click="refresh">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="tableData" :pagination="false" border style="width: 100%;"
              @selection-change="handleSelectionChange" class="table-style">
      <el-table-column prop="id" label="编号" width="200" align="center">
        <template v-slot="scpoe">
          <el-tag type="danger">
            <span>{{scpoe.row.id}}</span>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="componentName" label="药名" width="120" align="center">
        <template v-slot="scope">
          <el-tag type="success">
            <span>{{scope.row.componentName}}</span>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="imageurl" label="图片" width="180" align="center">
        <template v-slot="scope">
          <img :src="scope.row.imageurl" width="100px" height="70px">
        </template>
      </el-table-column>
      <el-table-column prop="character" label="成分" width="180" align="center"></el-table-column>
      <el-table-column prop="mainEffect" label="性状" width="180" align="center"></el-table-column>
      <el-table-column prop="malady" label="主要功效" width="190" align="center"></el-table-column>
      <el-table-column prop="clinicalPractice" label="临床应用及指南" width="900" align="center"></el-table-column>
      <el-table-column prop="specifications" label="规格" width="300" align="center"></el-table-column>
      <el-table-column prop="usageDosage" label="用法用量" width="400" align="center"></el-table-column>
      <el-table-column prop="note" label="注意事项" width="700" align="center"></el-table-column>
      <el-table-column prop="untowardReaction" label="不良反应" width="700" align="center"></el-table-column>
      <el-table-column prop="taboo" label="禁忌" width="300" align="center"></el-table-column>
      <el-table-column prop="drugInteractions" label="药物相互作用" width="700" align="center"></el-table-column>
      <el-table-column prop="carriedTandard" label="执行标准" width="190" align="center"></el-table-column>
      <el-table-column prop="storageMethods" label="贮藏方法" width="190" align="center"></el-table-column>
      <el-table-column prop="expirationDate" label="有效期" width="190" align="center"></el-table-column>
      <el-table-column el-table-column fixed="right" label="操作" width="270" align="center">
        <template v-slot="scope">
          <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" @click="addItem">添加</el-button>
          <el-button type="warning" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-popconfirm
            title="这是一段内容确定删除吗？"
            icon="el-icon-info"
            icon-color="red"
            @confirm="deleteItem(scope.row)"
            style="margin-left: 5px;white-space: nowrap"
          >
            <el-button :disabled="!deleteButton" slot="reference" type="danger" icon="el-icon-delete" size="mini">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <div style="text-align: right;padding: 10px 20px;" >
      <el-pagination
        @size-change="handlePageSizeChange"
        @current-change="handleCurrentPageChange"
        :current-page="page.page"
        :page-sizes="[5, 10, 15, 25, 30]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total" />
    </div>
    <!-- 编辑标签弹层 -->
    <div class="add-form">
      <el-dialog title="编辑" :visible.sync="dialogFormVisible4Edit" :modal="false">
        <el-form ref="dataEditForm" :model="formData" :rules="rules" label-position="right" status-icon label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="药名" prop="componentName">
                <el-input v-model="formData.componentName"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="成分" prop="character">
                <el-input v-model="formData.character"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="性状" prop="mainEffect">
                <el-input v-model="formData.mainEffect"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用法用量" prop="usageDosage">
                <el-input v-model="formData.usageDosage"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="有效期" prop="expirationDate">
                <el-input v-model="formData.expirationDate"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="不良反应" prop="untowardReaction">
                <el-input v-model="formData.untowardReaction"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="规格" prop="category">
                <el-input v-model="formData.specifications"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <div class="custom-upload-container">
                <div class="upload-title">图片上传</div>
                <el-upload
                  class="avatar-uploader"
                  :action="bashUrl + '/image/userImage'"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload">
                  <img v-if="imageUrl" :src="imageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="禁忌" prop="taboo">
                <el-input v-model="formData.taboo"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="药物相互作用" prop="drugInteractions">
                <el-input v-model="formData.drugInteractions"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="执行标准" prop="carriedTandard">
                <el-input v-model="formData.carriedTandard"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="贮藏方法" prop="storageMethods">
                <el-input v-model="formData.storageMethods"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="临床应用及指南" prop="clinicalPractice">
                <el-input v-model="formData.clinicalPractice" type="textarea" :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div  slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible4Edit = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateMedicine">确定</el-button>
        </div>
      </el-dialog>
    </div>
    <!--添加-->
    <div class="add-form">
      <el-dialog title="添加信息" :visible.sync="addDialogFormVisible" :modal="false">
        <el-form ref="dataEditForm" :model="formData" :rules="rules" label-position="right" status-icon label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="药名" prop="componentName">
                <el-input v-model="formData.componentName"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="成分" prop="character">
                <el-input v-model="formData.character"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="性状" prop="medicinalPart">
                <el-input v-model="formData.medicinalPart"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用法用量" prop="usageDosage">
                <el-input v-model="formData.usageDosage"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="有效期" prop="expirationDate">
                <el-input v-model="formData.expirationDate"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="不良反应" prop="untowardReaction">
                <el-input v-model="formData.untowardReaction"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="规格" prop="category">
                <el-input v-model="formData.specifications"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <div class="custom-upload-container">
                <div class="upload-title">图片上传</div>
                <el-upload
                  class="avatar-uploader"
                  :action="bashUrl + '/image/userImage'"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload">
                  <img v-if="imageUrl" :src="imageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="禁忌" prop="taboo">
                <el-input v-model="formData.taboo"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="药物相互作用" prop="drugInteractions">
                <el-input v-model="formData.drugInteractions"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="执行标准" prop="carriedTandard">
                <el-input v-model="formData.carriedTandard"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="贮藏方法" prop="storageMethods">
                <el-input v-model="formData.storageMethods"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="临床应用及指南" prop="clinicalPractice">
                <el-input v-model="formData.clinicalPractice" type="textarea" :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div  slot="footer" class="dialog-footer">
          <el-button @click="addDialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="insertMedicineItem">确定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import zhCn from 'element-ui/lib/locale/lang/zh-CN'
import request from '@/api/request'
import { TcMedicineDelete } from '@/api/medicine'

export default {
  data () {
    return {
      locale: zhCn,
      bashUrl: '',
      tableData: [],
      searchForm: {
        entrydate: null
      },
      page: {
        total: 7,
        currentPage: 1,
        pageSize: 3,
        queryString: ''
      },
      deleteButton: false,
      imageUrl: '',
      selectedRows: [],
      categoryOptions: [],
      formData: {
        imageurl: ''
      },
      rules: {
        componentName: [
          { required: true, message: '请输入药品名', trigger: 'blur' }
        ],
        character: [
          { required: true, message: '请输入成分', trigger: 'blur' }
        ],
        medicinalPart: [
          { required: true, message: '请输入性状', trigger: 'blur' }
        ],
        usageDosage: [
          { required: true, message: '请输入用法用量', trigger: 'blur' }
        ],
        expirationDate: [
          { required: true, message: '请输入有效期', trigger: 'blur' }
        ],
        unowardReaction: [
          { required: true, message: '请输入不良反应', trigger: 'blur' }
        ],
        specifications: [
          { required: true, message: '请输入规格', trigger: 'blur' }
        ],
        taboo: [
          { required: true, message: '请输入禁忌', trigger: 'blur' }
        ]
      },
      formList: {},
      dialogFormVisible4Edit: false,
      addDialogFormVisible: false
    }
  },
  created () {
    this.getDataChinesePatentDrugMedincine()
    this.getTcMedicineCategory()
    this.promisesion()
    this.bashUrl = this.$requestcode.defaults.baseURL
  },
  methods: {
    getTcMedicineCategory  () {
    },
    async getDataChinesePatentDrugMedincine () {
      const token = localStorage.getItem('token')
      const currentPage = this.page.currentPage
      const pageSize = this.page.pageSize
      const queryString = this.page.queryString
      request.get(`/chinese/chinesePatentDrug/${currentPage}/${pageSize}/` + '?chinesePatentDrug=' + queryString, {
        headers: {
          accept: 'application/json',
          'content-type': 'application/json',
          Authorization: `Bearer ${token}`
        }
      }).then(resp => {
        this.tableData = resp.data.rows
        this.page.total = resp.data.total
      }).catch(error => {
        this.handleAxiosError(error)
      })
      // 发送请求获取分页数据
    },
    onSubmit () {
      this.getDataChinesePatentDrugMedincine()
    },
    // 数据回显
    async handleUpdate (row) {
      const token = localStorage.getItem('token')
      this.dialogFormVisible4Edit = true
      request.get(`/chinese/${row.id}`, {
        headers: {
          accept: 'application/json',
          Authorization: `Bearer ${token}`
        }
      }).then(resp => {
        this.formData = resp.data.data
        // this.imageUrl = resp.data.imageUrl
      }).catch(error => {
        this.handleAxiosError(error)
      })
    },
    promisesion () {
      request.get('/req/request', {
        headers: {
          accept: 'application/json',
          Authorization: 'Bearer ' + localStorage.getItem('token')
        }
      }).then(resp => {
        // alert(resp.data.flag === true)
        if (resp.data.flag === true) {
          this.deleteButton = true
        } else {
          this.deleteButton = false
        }
      }).catch(error => {
        this.handleAxiosError(error)
      })
    },
    // 更新
    handleUpdateMedicine () {
      const token = localStorage.getItem('token')
      // alert(JSON.stringify(this.formData))
      this.$refs.dataEditForm.validate((valid) => {
        if (valid) {
          request.put('/chinese/chinesePatentDrug', this.formData, {
            headers: {
              accept: 'application/json',
              Authorization: `Bearer ${token}`
            }
          }).then(resp => {
            if (resp.data.flag === true) {
              this.$message({
                message: resp.data.message,
                type: 'success',
                center: true
              })
              this.imageUrl = ''
              this.dialogFormVisible4Edit = false
              this.getDataChinesePatentDrugMedincine()
              return
            }
            this.$message({
              message: resp.data.message,
              type: 'danger',
              center: true
            })
          }).catch(error => {
            this.handleAxiosError(error)
          })
        }
      })
    },
    // 选择
    handleSelectionChange (selection) {
      this.selectedRows = selection
    },
    deleteItem (row) {
      // const resp = await TcMedicineDelete(row.id)
      request.delete(`/chinese/${row.id}`, {
        headers: {
          accept: 'application/json',
          Authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then(resp => {
        if (resp.data.flag === true) {
          this.$message({
            message: resp.data.message,
            type: 'success',
            center: true
          })
          this.getDataChinesePatentDrugMedincine()
          return
        }
        this.$message({
          message: resp.data.message,
          type: 'danger',
          center: true
        })
      })
    },
    // 批量删除
    async batchDeletion () {
      if (this.selectedRows.length === 0) {
        this.$message({
          message: '请选择要删除的数据',
          type: 'warning',
          center: true
        })
        return
      }

      try {
        await this.$confirm('此操作将永久删除当前选中数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        const ids = this.selectedRows.map(row => row.id)
        // alert(ids)
        const resp = await TcMedicineDelete(ids)

        const data = resp.data
        if (data.flag === true) {
          this.$message({
            message: data.message,
            type: 'success',
            center: true
          })
          this.getData()
        } else {
          this.$message({
            message: data.message,
            type: 'error',
            center: true
          })
        }
      } catch (error) {
        // 如果是取消操作，不需要处理
        if (error.message !== 'cancel') {
          console.error('Error during batch deletion:', error)
          // 处理其他错误
        }
      }
    },
    refresh () {
      this.page.queryString = ''
      this.getDataChinesePatentDrugMedincine()
    },
    addItem () {
      this.formData = {}
      this.formList = {}
      this.addDialogFormVisible = true
    },
    insertMedicineItem () {
      this.$refs.dataEditForm.validate((valid) => {
        if (valid) {
          request.post('/chinese/chinesePatentDrug', this.formData, {
            headers: {
              accept: 'application/json',
              Authorization: `Bearer ${localStorage.getItem('token')}`
            }
          }).then(resp => {
            if (resp.data.flag === true) {
              this.$message({
                message: resp.data.message,
                type: 'success',
                center: true
              })
              this.addDialogFormVisible = false
              this.getDataChinesePatentDrugMedincine()
              return
            }
            this.$message({
              message: resp.data.message,
              type: 'danger',
              center: true
            })
            this.getDataChinesePatentDrugMedincine()
          }).catch(error => {
            this.handleAxiosError(error)
          })
        }
        if (!valid) {
          this.$notify({
            title: '提示',
            message: '请填写完整信息！！！',
            position: 'top-left',
            type: 'error',
            duration: 0
          })
        }
      })
    },
    handlePageSizeChange (pageSize) {
      this.page.pageSize = pageSize
      this.page.currentPage = 1 // 重置为第一页
      this.getDataChinesePatentDrugMedincine()
    },
    handleCurrentPageChange (currentPage) {
      this.page.currentPage = currentPage
      this.getDataChinesePatentDrugMedincine()
    },
    handleAvatarSuccess (res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      this.imageUrl = res.data
      // alert(this.imageUrl)
      this.formData.imageurl = res.data
    },
    beforeAvatarUpload (file) {
      const allowedFormats = ['image/jpeg', 'image/png', 'image/gif'] // 允许的文件格式

      const isAllowedFormat = allowedFormats.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 5

      if (!isAllowedFormat) {
        this.$message.error('上传头像图片只能是 JPG、PNG 或 GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isAllowedFormat && isLt2M
    },
    handleAxiosError (error) {
      // 检查是否是Axios的网络错误
      if (error.isAxiosError && error.response) {
        // 处理您的网络错误，例如显示用户友好的提示
        this.$message.error('网络请求失败，请稍后重试')
      } else {
        // 处理其他类型的错误
        this.$message.error('网络请求失败，发生错误，请稍后重试')
      }
    }
  }
}
</script>

<style>
.avatar-uploader-icon {
  font-size: 25px;
  color: #2667c4;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #bcbebf;
  margin: 20px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
.table-style {
  /*margin: 12px 12px 4px 1px;*/
}

.custom-upload-container {
  display: flex;
  align-items: center;
  margin-left: 25px;
}

.upload-title {
  margin-left: 10px;
  white-space: nowrap;
}
</style>
